<?php

/**
 * User: hufeng
 * Date: 2017/1/8
 * Desc: 桌面端消息通知server
 * ct: fiveTradeData-1@tradeLine-1(1股票id，五档数据，分时图)
 */

$ws = new swoole_websocket_server("0.0.0.0", 8076);
$ws->set(array(
        'daemonize' => true,
        'worker_num'=>1//TODO tip单线程 $GLOBALS能用，多线程的话，连接信息用redis来存储
    ));

$ws->on('start', function($serv) {
    cli_set_process_title("sdws_serve");
});

//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
    $ctype = $request->get['ct'];//客户端消息类型
    $ctypeArr = explode('@',$ctype);
    foreach ($ctypeArr as $val){
        $GLOBALS['glbWs'][$val][$request->fd] = $request->fd;
        $GLOBALS['glbWs']['clientType'][$request->fd][] = $val;
    }
});

//监听WebSocket消息事件,推送事件
$ws->on('message', function ($ws, $frame) {
    $msg =  $frame->data;
    $msgObj = json_decode($msg);
    foreach($GLOBALS['glbWs'][$msgObj->msgtype] as $client){
        $ws->push($client,$msg);
    }
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
    if(isset($GLOBALS['glbWs']['clientType'][$fd])){
        foreach ($GLOBALS['glbWs']['clientType'][$fd] as $val){
            unset($GLOBALS['glbWs'][$val][$fd]);
        }
        unset($GLOBALS['glbWs']['clientType'][$fd]);
    }
});
$ws->start();